package com.xiangjiayi.study.controller;

import dev.langchain4j.data.message.ImageContent;
import dev.langchain4j.data.message.TextContent;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Base64;

@RestController
@Slf4j
public class ImageModelController
{
    @Autowired
    private ChatModel chatModel;

    @Value("classpath:static/images/pmjt.png")
    private Resource resource;//import org.springframework.core.io.Resource;

    /**
    * @Description: 通过Base64编码将图片转化为字符串，结合ImageContent和TextContent
     * 一起发送到模型进行处理。
    * @Auther: zzyybs@126.com
     *测试地址：http://localhost:9006/image/call
    */
    @GetMapping(value = "/image/call")
    public String readImageContent() throws IOException
    {

//        1.第一步：图片转码，把图片内容转成二进制数组
        byte[] byteArray = resource.getContentAsByteArray();
        String base64Data = Base64.getEncoder().encodeToString(byteArray);

//        2.提示词指定：结合imageContent和TextContent给大模型处理
        UserMessage userMessage = UserMessage.from(
                TextContent.from("从以下图片中获取信息类型、信息来源。"),
                ImageContent.from(base64Data,"image/png")
        );

//        3.把usermessage也就是用户信息，这里包括用户请求消息和图片一起发给ai，并接收返回值
        ChatResponse chatResponse = chatModel.chat(userMessage);
        String result = chatResponse.aiMessage().text(); //那/把ai返回的消息转为string类型，然后打印出来

        System.out.println(result);

        return result;
    }
}
 
